import $ from '../../utils/tool'
const util = require('../../utils/util.js')
const app = getApp()

const defaultLogName = {
  work: '工作',
  rest: '休息'
}
const actionName = {
  stop: '停止',
  start: '开始'
}
const initDeg = {
  left: 45,
  right: -45,
}

Page({
  data: {
    remainTimeText: '',
    timerType: 'work',
    completed: false,
    isRunning: false,
    leftDeg: initDeg.left,
    rightDeg: initDeg.right,
    log: {},
    todayLogs: [],
    activeIndex: 0,
    totalFocusTime: 0, 
    totalFocusNumber: 0, 
    todayFocusTime: 0,
    todayFocusNumber: 0,
    showModal: false,
    workTime: null,
    restTime: null
  },
  onShow() {
    this.setData({
      logs: $.storage.get('logs')
    })
    app.globalData.logs = $.storage.get('logs')
    // 更新focus的全局变量，这样每次刷新不会丢失
    this.getFocus()
    if (this.data.isRunning) return
    // 待办事件跳转
    if(app.globalData.isTodo != 0) {
      let index = app.globalData.todoIndex
      let todoList = app.globalData.todoLists[index]
      let workTime = todoList.time
      let restTime = app.globalData.restTime
      let logName = todoList.name
      let nameObj = {detail: {value: logName}}
      this.setTime(workTime, restTime)
      const typeObj = {target: {dataset: {type: 'work'}}}
      this.changeLogName(nameObj)
      this.startTimer(typeObj)
      getApp().globalData.isTodo = 0
    }else {
      // setting中设置
      let workTime = app.globalData.workTime
      let restTime = app.globalData.restTime
      this.setTime(workTime, restTime)
    }
  },

  setTime(wkTime, rtTime) {
    let workTime = util.formatTime(wkTime, 'HH')
    let restTime = util.formatTime(rtTime, 'HH')
    this.setData({
      workTime: workTime,
      restTime: restTime,
      remainTimeText: workTime + ':00'
    })

    let logs = $.storage.get('logs')
    getApp().globalData.logs = logs
    this.setData({logs})
  },

  changeTime() {
    this.setData({
      showModal: true
    })
  },
  changeWorkTime(e) {
    getApp().globalData.workTime = e.detail.value
    let workTime = app.globalData.workTime
    let restTime = app.globalData.restTime
    this.setTime(workTime, restTime)
  },
  changeRestTime(e) {
    getApp().globalData.restTime = e.detail.value
    let workTime = app.globalData.workTime
    let restTime = app.globalData.restTime
    this.setTime(workTime, restTime)
  },
  hideModal() {
    this.setData({
      showModal: false
    })
  },

  //点击工作或休息
  startTimer(e) {
    let startTime = Date.now()
    let isRunning = this.data.isRunning
    let timerType = e.target.dataset.type //点击了哪个按钮,type是wxml传来的
    let showTime = this.data[timerType + 'Time'] //this.data[workTime] or this.data[restTime]，全局的数据，即点击工作上面展示工作倒计时，点击休息展示休息倒计时，单位min
    let keepTime = showTime * 60 * 1000 //ms
    let logName = this.logName || defaultLogName[timerType] //work转为工作，rest转为休息

    if (!isRunning) {
      wx.hideTabBar({
        animation: true,
      })
      this.timer = setInterval((function() {
        this.updateTimer()
        this.startNameAnimation()
      }).bind(this), 1000) //bind() 方法创建一个新的函数
    } else {
      wx.showTabBar({
        animation: true,
      })
      this.stopTimer()
    }

    this.setData({
      isRunning: !isRunning,
      completed: false,
      timerType: timerType,
      remainTimeText: showTime + ':00',
      taskName: logName
    })

    // 直接赋值data里的log，给记录页面用
    this.data.log = {
      name: logName,
      startTime: Date.now(),
      keepTime: keepTime,
      endTime: keepTime + startTime,
      action: actionName[isRunning ? 'stop' : 'start'],
      type: timerType
    }

    this.saveLog(this.data.log)
  },

  startNameAnimation() {
    //wx.createAnimation创建一个动画实例
    let animation = wx.createAnimation({
      duration: 450
    })
    //opacity透明度0-1，step表示一组动画完成
    animation.opacity(0.2).step()
    animation.opacity(1).step()
    this.setData({
      nameAnimation: animation.export() //最后通过动画实例的 export 方法导出动画数据传递给组件的 animation 属性
    })
  },

  stopTimer() {
    // 重置倒计时的圈
    this.setData({
      leftDeg: initDeg.left,
      rightDeg: initDeg.right
    })
    // 清干净timer， clearInterval取消由 setInterval 设置的定时器。
    this.timer && clearInterval(this.timer)
  },

  // 更新计时器
  updateTimer() {
    let log = this.data.log
    let now = Date.now()
    //Math.round() 四舍五入
    let remainingTime = Math.round((log.endTime - now) / 1000)
    //Math.floor() 去除小数位全舍
    let H = util.formatTime(Math.floor(remainingTime / (60 * 60)) % 24, 'HH')
    let M = util.formatTime(Math.floor(remainingTime / (60)) % 60, 'MM')
    let S = util.formatTime(Math.floor(remainingTime) % 60, 'SS')
    let halfTime

    // 更新显示的倒计时
    if (remainingTime > 0) {
      let remainTimeText = (H === "00" ? "" : (H + ":")) + M + ":" + S
      this.setData({
        remainTimeText: remainTimeText
      })
    } else if (remainingTime == 0) {  //倒计时完成
      this.setData({
        completed: true
      })
      this.stopTimer() // 停止计时器
      return
    }

    // 更新倒计时的外圈，分半
    halfTime = log.keepTime / 2
    // 前半圈
    if ((remainingTime * 1000) > halfTime) {
      this.setData({
        leftDeg: initDeg.left - (180 * (now - log.startTime) / halfTime)
      })
    } else {
      this.setData({
        leftDeg: -135
      })
      this.setData({
        rightDeg: initDeg.right - (180 * (now - (log.startTime + halfTime)) / halfTime)
      })
    }
  },

  changeLogName(e) {
    this.logName = e.detail.value
  },

  saveLog(log) {
    let logs = app.globalData.logs || []
    logs.unshift(log)     // unshift将新项目添加到数组的开头
    getApp().globalData.logs = logs
    this.getFocus()
    // 放入缓存，使其在不登录的情况下能使用统计
    $.storage.set('logs', logs)
  },

  // 处理log，获取每日focus和总共focus
  getFocus() {
    let logs = app.globalData.logs
    logs = Array.from(logs)
    if( logs.length % 2 == 0 ) {
      this.getTodayFocus()
      let totalFocusTime = 0
      let totalFocusNumber = 0
      for (let i = 0; i < logs.length; ) {
        let focusTime =  Math.round((logs[i].startTime - logs[i+1].startTime) / 1000)
        totalFocusTime += focusTime
        totalFocusNumber ++
        i = i + 2
      }
      this.setData({
        logs: logs,
        totalFocusTime: totalFocusTime,
        totalFocusNumber: totalFocusNumber
      })
      getApp().globalData.logs = logs
      getApp().globalData.totalFocusTime = totalFocusTime
      getApp().globalData.totalFocusNumber = totalFocusNumber
    }
    else {
      // console.log('还没结束')
    }
  },
  getTodayFocus() {
    let logs = app.globalData.logs
    let today = new Date(Date.now()).toLocaleDateString()
    let todayLogs = []
    let todayFocusTime = 0
    let todayFocusNumber = 0
    logs = Array.from(logs)
    if( logs.length % 2 == 0 ) {
      logs.forEach(item => {
        // 今日log
        let startDate = new Date(item.startTime).toLocaleDateString() || item.startTime
        item.showStartTime = new Date(item.startTime).toLocaleString() || item.startTime
        if ( startDate.indexOf(today) != -1 ){
          todayLogs.push(item)
        }
      })

      for (let i = 0; i < todayLogs.length; ) {
        let focusTime =  Math.round((todayLogs[i].startTime - todayLogs[i+1].startTime) / 1000) //bug，今晚做。明天结束
        todayFocusTime += focusTime
        todayFocusNumber ++
        i = i + 2
      }
      this.setData({
        todayLogs: todayLogs,
        todayFocusTime: todayFocusTime,
        todayFocusNumber: todayFocusNumber
      })
      getApp().globalData.todayLogs = todayLogs
      getApp().globalData.todayFocusTime = todayFocusTime
      getApp().globalData.todayFocusNumber = todayFocusNumber
    }
    else {
      console.log('还没结束')
    }
  }
})
